#!/bin/bash

read -p "Please enter the user name to join the docker group:" USERNAME

if [ -z "$USERNAME" ]; then
    echo "User name cannot be empty!"
    exit 1
fi

OS=$(cat /etc/os-release | grep -oE "(CentOS|Ubuntu|Debian)" | head -1)

# CentOS
centos_install() {
    yum remove -y docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine

    yum install -y yum-utils

    yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

    yum install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin

    systemctl start docker
}

# Ubuntu
ubuntu_install() {
    apt-get remove -y docker docker-engine docker.io containerd runc

    apt-get install -y apt-transport-https ca-certificates software-properties-common curl

    curl -fsSL https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu/gpg | sudo apt-key add -

    add-apt-repository "deb [arch=amd64] https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu \
    $(lsb_release -cs) stable"

    apt-get update

    #安装docker-ce
    apt-get install -y docker-ce

    systemctl start docker

    docker --version
}

# Debian
debian_install() {
    apt-get remove -y docker docker-engine docker.io containerd runc

    apt-get update

    apt-get install -y \
        apt-transport-https \
        ca-certificates \
        curl \
        gnupg2 \
        software-properties-common

    curl -fsSL https://mirrors.ustc.edu.cn/docker-ce/linux/debian/gpg | sudo apt-key add -

    add-apt-repository \
        "deb [arch=amd64] https://mirrors.ustc.edu.cn/docker-ce/linux/debian \
        $(lsb_release -cs) \
        stable"

    apt-get update

    apt-get install -y docker-ce docker-ce-cli containerd.io

    systemctl start docker

    docker --version
}

# config mirrors
config_daemon() {
    local num=$1

    local mirrors=(https://registry.docker-cn.com https://docker.mirrors.ustc.edu.cn https://6vlccsld.mirror.aliyuncs.com https://hub-mirror.c.163.com)

    echo -e "{ \"registry-mirrors\": [\"${mirrors[$num]}\"] }" >/etc/docker/daemon.json

    systemctl restart docker

    docker info
}

# config group
config_group() {
    groupadd docker

    gpasswd -a $USERNAME docker

    newgrp docker
}

main() {
    if [ $OS == "CentOS" ]; then
        centos_install
    elif [ $OS == "Ubuntu" ]; then
        ubuntu_install
    elif [ $OS == "Debian" ]; then
        debian_install
    else
        echo "Only (CentOS Ubuntu Debian) is supported, other systems are not supported !"
    fi

    config_daemon 1

    config_group
}

main
